import request from '@/api/request'
import { reactive } from 'vue'

class Store {
  constructor(data = []) {
    this.view = reactive({
      data,
      total: 0,
      page: 1,
      pageSize: 0,
      status: 0
    })
    this.loading = false
    this.proxy = new AxiosProxy()
  }

  async getData(config) {
    let url = config?.url || this.url
    let params = config?.params || {}

    await this.proxy.sendGetRequest(url, params, this)
  }
}

class Module {}

class AxiosProxy {
  // 具体配置
  constructor(config) {
    this.config = config
    this.loading = false
  }
  async sendGetRequest(url, params, store) {
    try {
      // 状态
      this.loading = true
      store.view.status = 1
      // 请求
      let result = await request.get(url, params)
      // 结果
      if (this.jsonSuccess(result)) {
        store.view.status = 2
        store.view.data = this.jsonData(result)
        store.view.total = this.jsonTotal(result)
        store.view.page = this.jsonPage(result)
        store.view.pageSize = this.jsonPageSize(result)
      }
    } catch (error) {
      // 错误捕捉并处理
      store.view.status = 3
      console.log(error)
    } finally {
      // 无论结果如何 都代表请求执行结束了
      this.loading = false
    }
  }
  sendPostRequest(url, params) {}
  cancelRequest() {}

  // 数据序列化是根据返回值的不同对函数进行调整
  // 暂时处理成这个样子 并不代表最终方案
  jsonSuccess(res) {
    return res?.status
  }
  jsonData(res) {
    return res.data.data
  }
  jsonTotal(res) {
    return res.data.total
  }
  jsonPage(res) {
    return res.data.page
  }
  jsonPageSize(res) {
    return res.data.pageSize
  }
}

export default Store
